import React, { Component } from 'react';
import { Button, Input, Table, Modal, Icon, message, Empty } from 'antd';
import Operator from './operator';
import AddEditModal from './add-edit-modal';
import PropTypes from 'prop-types';
import copyToClipboard from '@util/copy-to-clipboard';
import { get, clone } from 'lodash';
import { getUsers } from '@api/user';
/**
 * 隐藏前端账号互通的开关，详见工单ZOOMEYEBE-2389
 */
// import { getScanvConfig, updateScanvConfig } from '@api/scanv';
import { connect } from 'react-redux';
import './index.less';

const { Search } = Input;

class UserManage extends Component {
  static propTypes = {
    maxUserNumber: PropTypes.number
  };
  constructor(props) {
    super(props);

    this.state = {
      page: 1,
      pageSize: 10,
      search: '',

      password: '',
      users: [],
      total: 0,
      isAddSucceed: false,
      addEditModalType: '',
      isConfigingUser: false,
      isLoadingUsers: false,
      statusModalVisble: false,
      currentUser: null,
      isLoadingScanv: false,
      scanvIsOpen: false,
      disabledScanv: false,
      scanvConfig: {}
    };
  }

  componentDidMount() {
    this.loadUsers();
    /**
     * 隐藏前端账号互通的开关，详见工单ZOOMEYEBE-2389
     */
    // this.loadScanvConfig();
  }

  loadUsers = () => {
    const { page, pageSize, search } = this.state;

    this.setState({ isLoadingUsers: true });
    getUsers({ page, pageSize, search })
      .then(res => {
        const users = get(res, 'data.data.list', []);
        //eslint-disable-next-line
        users.forEach(user => (user.role_id = get(user, 'role_oid._id', '')));
        const total = get(res, 'data.data.count', []);
        this.setState({
          users,
          total
        });
      })
      .finally(() => {
        this.setState({ isLoadingUsers: false });
      });
  };

  /**
   * 隐藏前端账号互通的开关，详见工单ZOOMEYEBE-2389
   */
  // loadScanvConfig = () => {
  //   this.setState({ isLoadingScanv: true });
  //   getScanvConfig()
  //     .then(res => {
  //       const scanvConfig = get(res, 'data.data.scanvConfig', {});
  //       const isOpen = get(scanvConfig, 'isOpen', false);
  //       this.setState({
  //         scanvConfig,
  //         scanvIsOpen: isOpen
  //       });
  //     })
  //     .finally(() => {
  //       this.setState({ isLoadingScanv: false, disabledScanv: false });
  //     });
  // };

  getColumns = () => {
    const columns = [
      {
        title: '用户名',
        className: 'user-name',
        dataIndex: 'username'
      },
      {
        title: '姓名',
        className: 'user-real-name',
        dataIndex: 'nickname'
      },
      {
        title: '用户类型',
        className: 'user-type',
        dataIndex: 'role_oid.name'
      },
      {
        title: '邮箱',
        className: 'user-email',
        dataIndex: 'email'
      },
      {
        title: '手机号',
        dataIndex: 'phone'
      },
      {
        title: '创建日期',
        className: 'created-time',
        dataIndex: 'created'
      },
      {
        title: '失效日期',
        className: 'expired-time',
        dataIndex: 'expired'
      },
      {
        title: '操作',
        className: 'user-operate',
        key: 'operator',
        width: 100,
        render: row => {
          const operator = (
            <Operator
              row={row}
              onEditUser={() => this.onEditUser(row)}
              afterReset={password =>
                this.setState({ password, statusModalVisble: true, isAddSucceed: false })
              }
              afterDelete={this.loadUsers}
            />
          );
          return operator;
        }
      }
    ];

    return columns;
  };

  onEditUser = user => {
    this.setState({
      addEditModalType: 'edit',
      currentUser: clone(user)
    });
  };

  onCloseStatueModal = () => {
    this.setState({
      statusModalVisble: false
    });
  };

  onCancelAddEdit = () => {
    this.setState({
      addEditModalType: ''
    });
  };

  onAddUser = () => {
    const { maxUserNumber } = this.props;
    const { total } = this.state;
    if (total >= maxUserNumber) {
      message.error('可添加用户数已达上限');
      return;
    }
    this.setState({
      addEditModalType: 'add',
      currentUser: null
    });
  };

  onCopyPassword = () => {
    const { password } = this.state;
    const res = copyToClipboard(password);
    if (res) {
      message.success('成功');
    } else {
      message.error('失败');
    }
  };

  onSearch = search => {
    this.setState(
      {
        search
      },
      this.loadUsers
    );
  };

  onSearchChange = e => {
    this.setState({
      search: e.target.value
    });
  };

  onTableChange = ({ current: page, pageSize }) => {
    document.getElementsByClassName('ant-layout-content')[0].scrollTop = 0;
    this.setState(
      {
        page,
        pageSize
      },
      this.loadUsers
    );
  };

  onAddEditSuccess = (password, type) => {
    let body = { addEditModalType: '' };
    if (password) {
      body.password = password;
      body.statusModalVisble = true;
    } else {
      message.success('编辑用户成功');
    }
    body.isAddSucceed = type ? false : true;
    this.setState(body, this.loadUsers);
  };

  /**
   * 隐藏前端账号互通的开关，详见工单ZOOMEYEBE-2389
   */
  // onToggleScanvIsOpen = checked => {
  //   this.setState({ isLoadingScanv: true, scanvIsOpen: checked, disabledScanv: true });
  //   updateScanvConfig({ isOpen: checked }).then(res => {
  //     const data = get(res, 'data.data', {});
  //     const isOpen = get(data, 'scanvConfig.isOpen', false);
  //     const result = get(res, 'data.result', false);
  //     if (!result) {
  //       this.setState({ isLoadingScanv: false, scanvIsOpen: !checked, disabledScanv: false });
  //       return;
  //     }
  //     this.setState({ isLoadingScanv: false, scanvIsOpen: isOpen, disabledScanv: false });
  //   });
  // };

  render() {
    const {
      page,
      pageSize,
      total,
      search,
      users,
      isLoadingUsers,
      statusModalVisble,
      addEditModalType,
      password,
      currentUser,
      isAddSucceed
      /**
       * 隐藏前端账号互通的开关，详见工单ZOOMEYEBE-2389
       */
      // isLoadingScanv,
      // scanvIsOpen,
      // disabledScanv
    } = this.state;

    const columns = this.getColumns();
    const pagination = {
      current: page,
      pageSize: pageSize,
      total: total,
      showQuickJumper: true,
      showSizeChanger: true,
      showTotal: num => `共 ${num} 条`,
      size: 'small'
    };

    const addEditStatusModalFooter = [
      <Button className="close" key="0" onClick={this.onCloseStatueModal}>
        关闭
      </Button>,
      <Button className="copy" key="1" type="primary" onClick={this.onCopyPassword}>
        复制密码
      </Button>
    ];

    return (
      <div className={'user-center'}>
        <div className="head">
          <div className="head-left">
            <Button className="add-user-btn" type="primary" onClick={this.onAddUser}>
              添加用户
            </Button>
            <span className="now-user">当前用户数: {total}</span>
            {/**
             * 隐藏前端账号互通的开关，详见工单ZOOMEYEBE-2389
             */
            /* <div className="toggle-scanv">
              <span>慧眼账号互通 </span>
              <Switch
                checkedChildren="on"
                unCheckedChildren="off"
                loading={isLoadingScanv}
                checked={scanvIsOpen}
                disabled={disabledScanv}
                onChange={this.onToggleScanvIsOpen}
              />
            </div> */}
          </div>
          <div className="head-right">
            <Search
              placeholder="请输入用户名/姓名"
              value={search}
              enterButton
              onSearch={this.onSearch}
              onChange={this.onSearchChange}
            />
          </div>
        </div>
        <Table
          rowKey="_id"
          columns={columns}
          pagination={pagination}
          dataSource={users}
          loading={{ spinning: isLoadingUsers, tip: '加载中' }}
          locale={{
            emptyText: (
              <Empty
                description={isLoadingUsers ? ' ' : '暂无数据'}
                image={Empty.PRESENTED_IMAGE_SIMPLE}
              />
            )
          }}
          onChange={this.onTableChange}
          className="user-table"
        />
        <AddEditModal
          title={addEditModalType === 'add' ? '添加用户' : '编辑用户'}
          visible={Boolean(addEditModalType)}
          onCancel={this.onCancelAddEdit}
          onSuccess={this.onAddEditSuccess}
          values={currentUser}
        />
        <Modal
          maskClosable={false}
          className={'user-center-add-edit-status-modal'}
          visible={statusModalVisble}
          title={null}
          footer={addEditStatusModalFooter}
          onCancel={this.onCloseStatueModal}
        >
          <div className="content">
            <Icon className="icon" type={'check-circle'} theme="twoTone" />
            <p className="info">{isAddSucceed ? '添加用户成功' : '重置用户密码成功'}</p>
            <p className="password">
              {isAddSucceed ? `用户初始密码: ${password}` : `用户重置密码${password}`}
            </p>
          </div>
        </Modal>
      </div>
    );
  }
}

const mapStateToProps = state => {
  return {
    maxUserNumber: get(state, 'auth.cert.max_user_number', 0)
  };
};

export default connect(mapStateToProps)(UserManage);
